﻿using System;
using System.Net;
using System.Net.Sockets;

namespace EastForceCondensor.CommCtrl
{
    interface ISocket
    {
        bool Connect(string ipAddr, int port);
        void Disconnect();
        bool ReadData(ref byte[] readData, ref int byteNum);
    }

    class UdpMgmt : ISocket
    {
        private UdpClient m_udpClient = new UdpClient();
        private IPEndPoint m_localIP = new IPEndPoint(IPAddress.Parse("192.168.100.151"), 8811);
        private IPEndPoint m_remoteIP;
        private IPEndPoint m_remoteIP_const;
        private bool m_IsConnected = false;
        //private byte[] m_dataPackage = new byte[1441];//72*20+1=1441

        public UdpMgmt()
        {
            m_localIP = new IPEndPoint(IPAddress.Parse("192.168.100.150"), 8810);
        }
        public bool Connect(string ipAddr, int port)
        {
            try
            {
                m_udpClient = new UdpClient(m_localIP);
                m_remoteIP = new IPEndPoint(IPAddress.Parse(ipAddr), port);
                m_remoteIP_const = new IPEndPoint(IPAddress.Parse(ipAddr), port);
                m_IsConnected = true;
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                m_IsConnected = false;
                return false;
            }

            return true;
        }
        public void Disconnect()
        {
            if (m_IsConnected)
                m_udpClient.Close();
        }
        public void SendData(byte[] sendData, int dataNum)
        {
            try
            {
                m_udpClient.Send(sendData, dataNum, m_remoteIP_const);
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
            }
        }
        public bool ReadData(ref byte[] readData, ref int byteNum)
        {
            try
            {
                readData = m_udpClient.Receive(ref m_remoteIP);
                byteNum = readData.Length;
                return true;
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                return false;
            }
        }
    }
}
